-- -*- Mode: lua; lua-indent-level: 2; tab-width: 2 -*-

local _G = _G
local TEXT = TEXT
local strlower = strlower
local next = next
local tinsert = table.insert
local tsort = table.sort
local strjoin = strjoin

local function SlashConflict_Print(msg)
   local info = ChatTypeInfo["SYSTEM"]
   DEFAULT_CHAT_FRAME:AddMessage(msg, info.r, info.g, info.b, info.id)
end

local function SlashConflict_FindConflicts()
	local commands = {}
	local values = {}
	local valueCmd = {}

	-- Find all command strings
	for index, value in pairs(SlashCmdList) do
		local form = 1
		local cmdString = TEXT(_G["SLASH_"..index..form])
		while ( cmdString ) do
			values[value] = index
			cmdString = strlower(cmdString)
			if not commands[cmdString] then commands[cmdString] = {} end
			if not valueCmd[value] then valueCmd[value] = cmdString end
			commands[cmdString][index] = value
			form = form + 1
			cmdString = TEXT(_G["SLASH_"..index..form])
		end
	end

	-- Look for conflicts
	for cmdString, indices in pairs(commands) do
		local index,value = next(indices)
		if next(indices,index) then
			-- We have a conflict
			local indexnames = {}
			for index,values in pairs(indices) do
				tinsert(indexnames,index)
			end
			tsort(indexnames)
			SlashConflict_Print(("SlashConflicts: Command %s conflicts among: %s"):format(cmdString,strjoin(", ",unpack(indexnames))))
		else
			-- Value is callable
			values[value] = nil
		end
	end

	-- Look for uncallable commands
	for value, index in pairs(values) do
		SlashConflict_Print(("SlashConflicts: Possibly uncallable command %s for: %s"):format(valueCmd[value],index))
	end
end

SLASH_SLASHCONFLICTS1 = "/SlashConflicts"
SlashCmdList["SLASHCONFLICTS"] = SlashConflict_FindConflicts
